package org.phpgwt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.ext.BadPropertyValueException;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.LinkerContext;
import com.google.gwt.core.ext.linker.ConfigurationProperty;

public class Utility {

	public static ArrayList<String> readFileFromClasspath(String classpath) throws IOException {
		ArrayList<String> ret = new ArrayList<String>();

		BufferedReader reader = new BufferedReader(new InputStreamReader(Utility.class.getClassLoader().getResourceAsStream(classpath)));

		for (String input = reader.readLine(); input != null; input = reader.readLine()) {
			ret.add(input);
		}

		return ret;
	}

	public static String arrayListToString(List<String> list) {
		String ret = "";

		for (String line : list) {
			ret += line + "\n";
		}

		return ret;
	}

	public static String getConfigFilePath(LinkerContext context) {
		for (ConfigurationProperty prop : context.getConfigurationProperties()) {
			if (prop.getName().equals("phpgwt")) {
				return prop.getValues().get(0);
			}
		}

		return null;
	}

	public static String getConfigFilePath(GeneratorContext context) {
		try {
			return context.getPropertyOracle().getConfigurationProperty("phpgwt").getValues().get(0);
		} catch (BadPropertyValueException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String getShortClassName(String fullyQualifiedName) {
		return fullyQualifiedName.substring(fullyQualifiedName.lastIndexOf('.') + 1);
	}

	public static String firstLetterToUpperCase(String str) {
		if (str.length() <= 1) {
			return str.toUpperCase();
		} else {
			return str.substring(0, 1).toUpperCase() + str.substring(1);
		}
	}
	
	public static List<String> getConfigurationProperties(LinkerContext context, String name) {
		for (ConfigurationProperty configurationProperty : context.getConfigurationProperties()) {
			if (name.equals(configurationProperty.getName())) {
				return configurationProperty.getValues();
			}
		}

		return null;
	}
}
